package com.lx.chong.utils.websocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * webSocket工具类
 *
 * @author: whh
 * @date: 2018/1/6
 */
@Component
@ServerEndpoint("/webSocketAdd")
@Slf4j
public class SocketUtil {
    private Session session;

    private static CopyOnWriteArraySet<SocketUtil> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        System.out.println("[webSocket消息]有新的连接, 总数: " + webSocketSet.size());
        log.info("[webSocket消息]有新的连接, 总数:{}", webSocketSet.size());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("[webSocket消息]连接断开, 总数:{}", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("[webSocket消息]收到客户端发来的消息:{}", message);
        if (StringUtils.isNotBlank(message) && message.equals("ping")) {
            sendMessage(message);
        }
    }

    public void sendMessage(String message) {
        for (SocketUtil webSocket : webSocketSet) {
            log.info("[webSocket消息]广播消息, message={}", message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * springboot内置tomcat的话，需要配一下这个。。如果没有这个对象，无法连接到websocket
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
